package com.common.baselibrary.mvp;
import android.view.View;

import java.util.ArrayList;
import java.util.List;


/**
 * MVP Fragment 基类
 * Created by xuyougen on 2018/4/17.
 */

public abstract class BaseMvpFragment<V extends BaseView, P extends BasePresenter<V>> extends LazyLoadFragment implements BaseView, MVPLifecycleObservable {

    private P presenter;
    private LoadingDialog loadingDialog;
    private List<MVPLifecycleObserver> lifecycleObservers;

    {
        lifecycleObservers = new ArrayList<>();
    }

    @Override
    public void init(View view) {
        loadingDialog = new LoadingDialog.Builder(getContext()).build();
        presenter = createPresenter();
        presenter.attach((V) this);
    }


    @Override
    public void registerMVPLifecycleObserver(MVPLifecycleObserver observer) {
        lifecycleObservers.add(observer);
    }

    protected abstract P createPresenter();

    public P getPresenter() {
        return presenter;
    }

    @Override
    public void showLoading() {
        showLoading("加载中");
    }

    @Override
    public void showLoading(String text) {
        if (loadingDialog == null) return;
        loadingDialog.setText(text);
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    @Override
    public void hideLoading() {
        if (loadingDialog == null) return;
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    @Override
    public void onNoNetwork() {
        for (MVPLifecycleObserver observer : lifecycleObservers) {
            observer.onNoNetwork();
        }
    }

    @Override
    public void onTimeout() {
        for (MVPLifecycleObserver observer : lifecycleObservers) {
            observer.onTimeout();
        }
    }

    @Override
    public boolean noDisposeAfterDetach() {
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            presenter.detach();
            lifecycleObservers.clear();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
